<?php

namespace App\Api\Controllers\user;

use App\Admin\Service\AliyunOss;
use App\Api\Bases\BaseController;
use App\Api\Manages\CommonController;
use App\Api\Models\Blanace;
use App\Api\Models\Member;
use App\Api\Models\PromotionOrderlist;
use App\Api\Services\JsonService;
use App\Api\Services\UniqueStr;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;


class MembersController extends BaseController
{

    /**
     * 发送手机验证码
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function phoneVerify(Request $request)
    {
        try {
            $params = $this->validate($request, [
                'phone' => 'required|mobile',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        $phone = $params['phone'];
        $phoneNum = cache('phone_num_' . $phone) ?? null;
        if ($phoneNum >= 5) return JsonService::fail('每天最多只能发送五次验证码');
        $lastTime = cache('last_time' . $phone) ?? null;
        if ((time() - $lastTime) < 60) return JsonService::fail('验证码获取太过频繁，请一分钟后再试');
        //生成四位数字验证码
        $number = CommonController::makeRandomNumber();
        $result = CommonController::sendPhoneCode($phone, $number);
        if (isset($result['code']) && $result['code'] == 10000) {
            //短信接口调用成功
            cache(["phone_" . $phone => $number], 180) ?? null;
            cache(["last_time" . $phone => time()], 3600) ?? null;
            $phoneNum++;
            cache(['phone_num_' . $phone => $phoneNum], 3600 * 24) ?? null;
            return JsonService::success('验证码发送成功');

        } else {
            return JsonService::fail('服务器繁忙，请稍候再试');
        }

    }

    /**
     * 手机号注册
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function registered(Request $request)
    {

        try {
            $params = $this->validate($request, [
                'phone' => 'required|mobile|unique:cmc_members,phone',
                'verify' => 'required|digits:4'
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        list($phone, $verify) = array_values($params);
        $phpCode = cache("phone_" . $phone) ?: null;
        if ($verify != $phpCode) return JsonService::fail('验证码错误');
        $uniquePhone = Member::uniquePhone($phone);
        if ($uniquePhone) return JsonService::fail('该手机号码已注册 ,请确认是否本人');
        $username = UniqueStr::uniqueId();
        $data = [
            'username' => $username,
            'nickname' =>$username,
            'phone' => $phone,
            'avatar' =>'',
            'status' => 1
        ];
        $member_id = Member::saveData($data);
        if (!$member_id) return JsonService::fail('验证失败,');
        return JsonService::success('验证通过', $member_id);
    }

    public function password(Request $request)
    {
        try {
            $params = $this->validate($request, [
                'member_id'=>'required|integer',
                'password' => 'required|alpha_dash|min:6|max:16'
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        if ($params['password'] == '123456') return JsonService::fail('密码不能与初始密码相同');

        $pwd = CommonController::encrypt($params['password']);
        $model = Member::saveData(['password' => $pwd, 'status' => 3], ['member_id' => $params['member_id'], 'status' => 1]);
        if (!$model) return JsonService::fail('注册失败');
        return JsonService::success('注册成功');

    }

    /**
     * 修改密码
     * @param Request $request
     * @return array
     */
    public function savePassword(Request $request)
    {

        try {
            $params = $this->validate($request, [
                'username' => 'required|alpha_dash|max:16',
                'old_password' => 'required|alpha_num|min:6|max:16',
                'password' => 'required|alpha_num|min:6|max:16'
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        if ($params['password'] == '123456') JsonService::fail('新密码不能为初始密码相同');
        //要修该的新密码
        $newPwd = CommonController::encrypt($params['password']);
        //用户输入的旧密码
        $oldPwd = CommonController::encrypt($params['old_password']);
        //数据库的用户密码
        $password = Member::Password($params['username']);
        if ($oldPwd != $password) return JsonService::fail('旧密码不正确');
        if ($newPwd == $oldPwd) return JsonService::fail('新密码不能与最近使用密码相同');

        $result = Member::saveData(['password'=>$newPwd],['username' =>$params['username']]);
        if (!$result) return JsonService::fail('密码修改失败');
        return JsonService::success('密码修改成功');

    }

    /**
     * 用户信息
     * @return array
     */
    public function memberInfo(Request $request)
    {
        try {
            $params = $this->validate($request, [
                'member_id' => 'required|integer',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        $filed = ['member_id', 'username','nickname','avatar'];
        $memberInfo = Member::memberInfo($params['member_id'], $filed);
        if (!$memberInfo) return JsonService::fail('查询修改失败');
        return JsonService::success('查询成功', $memberInfo);
    }

    /**
     * 修改昵称
     * @param Request $request
     */
    public function saveNickname(Request $request)
    {

        try {
            $params = $this->validate($request, [
                'member_id'=>'required|integer',
                'nickname' => 'required|alpha_dash|min:2|max:12'
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        $memberId = $params['member_id'];
        $model = Member::saveData($params, ['member_id' => $memberId]);
        if (!$model) return JsonService::fail('昵称修改失败');
        return JsonService::success('昵称修改成功',$params);

    }

    /**
     * 文件云存储
     * @param Request $request
     * @return array
     */
    public function upFile(Request $request)
    {
        try {
            $params = $this->validate($request, [
                'file' => 'required|image',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        $result = \App\Api\Services\AliyunOss::aliOss($params['file']);
        if (!$result) return JsonService::fail('文件上传失败');
        return JsonService::success('文件上传成功', $result);
    }

    /**
     * 修改用户头像
     * @param Request $request
     * @return array
     */
    public function saveAvatar(Request $request)
    {
        try {
            $params = $this->validate($request, [
                'member_id' => 'required|integer',
                'avatar' =>'required'
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        $model = Member::saveData($params, ['member_id' => $params['member_id']]);
        if (!$model) return JsonService::fail('头像修改失败');
        return JsonService::success('头像修改成功',$params);
    }

    /**
     * 用户余额 和 积分
     * @param Request $request
     * @return array
     */
    public function balance(Request $request){
        try {
            $params = $this->validate($request, [
                'member_id' => 'required|integer',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        $filed = ['member_id','point','balance'];
        $balance =  Member::memberInfo($params['member_id'],$filed);
        if (!$balance) return JsonService::fail('余额查询失败');

        return JsonService::success('余额查询成功',$balance);
    }

    /**
     * 用户总充值
     * @param Request $request
     * @return array
     */
    public function recharge(Request $request)
    {
        try{
            $params = $this->validate($request,[
                'member_id'=>'required|integer',
            ]);
        } catch (ValidationException $validationException){
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        $memberId = (int)$params['member_id'];

        //总充值
        $totalUp = (int)Blanace::totalTop($memberId);

        if(!$totalUp){
            return JsonService::fail('暂未充值');
        }
        return JsonService::success('查询成功',$totalUp);
    }

    /**
     * 用户消费记录查询接口
     * @param Request $request
     * @return array
     */
    public function consumption(Request $request)
    {
        try {
            $params = $this->validate($request,[
                'member_id'=>'required|integer',
            ]);
        }catch (ValidationException $validationException){
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        $memberId = (int)$params['member_id'];

        $allowField = ['total_money','coupon_price','pay_time','pay_type','oderlist_name'];

        //消费记录
        $consumptionData = PromotionOrderlist::getRecordsData($memberId,$allowField);

        if($consumptionData){
            return JsonService::success($consumptionData);
        }
        return JsonService::fail('暂无消费记录','',1003);
    }
}


